import {Injectable} from '@angular/core';
import {Authority} from './Authority';
import {GnLoginUser} from './LoginUser';
import {GnMenu} from './Menu';

@Injectable()
export class GnSiteInfo {

  title: string;
  loginUrl: string;
  logoutUrl: string;
  iconFontUrl: string;
  showBreadcrumb = false;
  siderMenuTheme = 'dark';
  authSiderMenu: GnMenu[] = [];
  siteAuthorities: Authority[] = [];
  siderMenu: GnMenu[] = [];

  constructor(private loginUser: GnLoginUser) {
  }

  filterMenu(): void {
    this.authSiderMenu = this.getAuthorityMenu(this.siderMenu, '');
  }

  getAuthorityMenu(menus: GnMenu[], parentPath: string): GnMenu[] {
    if (this.loginUser.authorities && menus) {
      return menus.map(menu => {
        const path = parentPath + (menu.router || '');
        if (menu.authority) {
          const authority = this.siteAuthorities?.find((item) => item.url === path);
          if (!authority) {
            this.siteAuthorities.push({url: path, authority: menu.authority});
          }
        }

        return {
          title: menu.title,
          router: menu.router,
          icon: menu.icon,
          authority: menu.authority,
          subMenu: this.getAuthorityMenu(menu.subMenu, path)
        };
      }).filter(menu => this.loginUser.authorities.includes(menu.authority)
        || ((!menu.subMenu || menu.subMenu.length === 0) && !menu.authority)
        || (menu.subMenu && menu.subMenu.length > 0));
    } else {
      return menus;
    }
  }
}
